package com.dman.multi.cmd;

import org.apache.pivot.collections.List;
import org.apache.pivot.util.Vote;
import org.apache.pivot.wtk.Alert;
import org.apache.pivot.wtk.Dialog;
import org.apache.pivot.wtk.DialogStateListener;
import org.apache.pivot.wtk.MessageType;
import org.apache.pivot.wtk.Prompt;

import com.dman.multi.core.Download;
import com.dman.multi.ui.DMan;

public class GUIRestartCommand implements Command {
	
	private DMan parent;
	private List<Download> downloadList;
	private Alert alert;

	public GUIRestartCommand(DMan parent, List<Download> downloadList) {
		super();
		this.parent = parent;
		this.downloadList = downloadList;
		alert = new Alert();
		alert.setMessageType(MessageType.QUESTION);
		alert.setMessage("Are you sure to restart the selected download?");
		Alert.OptionSequence opseq = alert.getOptions();	
		opseq.remove(0, opseq.getLength());
		opseq.add("Yes");
		opseq.add("No");
		alert.setModal(true);
		alert.getDialogStateListeners().add(new DialogStateListener.Adapter(){
			@Override
			public Vote previewDialogClose(Dialog dialog, boolean result) {
				if(alert.getSelectedOptionIndex() < 1){
					int index = GUIRestartCommand.this.parent.getSelectedTableViewIndex();
					if(index >= 0){
						Download d = GUIRestartCommand.this.downloadList.get(index);
						try{
							d.restart();
						} catch(Exception e){
							Prompt.prompt("Unable to restart download", GUIRestartCommand.this.parent);						
						}
					}
				}
				
				return Vote.APPROVE;
			}
		});
	}

	@Override
	public void execute() {
		alert.open(parent);
	}

}
